/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jsysacc.asistencia.view.gui.maestros;

import com.cerd.util.BaseSP01.JUtilBaseSP01;
import com.jsysacc.asistencia.model.beans.maestros.Via;
import com.jsysacc.asistencia.model.logic.maestros.ViaLogic;
import com.jsysacc.asistencia.view.resources.commons.JLogicInterfaz;
import com.jsysacc.asistencia.view.resources.commons.JTextFieldToUpperCase;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;

/**
 *
 * @author Carlos
 */
public class FormDialogMantVia extends javax.swing.JDialog implements JLogicInterfaz {

    ViaLogic logic = new ViaLogic();
    private boolean esNuevo;
    private String codVia;

    //variable locales
    private Via entityVia;

    private final ResourceBundle rbMensajes = ResourceBundle.getBundle("com.jsysacc.asistencia.view.resources.commons.Mensajes");
    private final JUtilBaseSP01 JUB = JUtilBaseSP01.JUtilBaseSP01;

    /**
     * Creates new form FormDialogMantVia
     */
    public FormDialogMantVia(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    private void limpiar() {
        this.jtxtCodigo.setText("");
        this.jtxtDescripcion.setText("");
        this.jtxtAbreviatura.setText("");
        this.jchkEstado.setSelected(false);
        this.jtxtDescripcion.requestFocus();
    }

    //metodo para saber si viene del modificar o del nuevo
    private void llenarData() {

        if (esNuevo) {
            limpiar();
        } else {
            try {
                Via oVia = logic.getByPk(codVia);
                if (JUB._vacio(oVia)) {
                    JOptionPane.showMessageDialog(this, " REGISTRO CON CÓDIGO: " + codVia + " NO EXISTE EN LA BD.", rbMensajes.getString("MSG_MEN_PRI"), 0);
                } else {
                    setEntity(oVia);
                    this.jtxtDescripcion.requestFocus();
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), rbMensajes.getString("MSG_MEN_PRI"), 0);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbtnAceptar = new javax.swing.JButton();
        jbtnCancelar = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtxtCodigo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtxtDescripcion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtxtAbreviatura = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jchkEstado = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jbtnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_24_24/btn_ok_24.png"))); // NOI18N
        jbtnAceptar.setText("Aceptar");
        jbtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAceptarActionPerformed(evt);
            }
        });

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_24_24/btn_cancelar_24.png"))); // NOI18N
        jbtnCancelar.setText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jTabbedPane1.setFocusable(false);

        jLabel1.setText("Código");

        jtxtCodigo.setEditable(false);
        jtxtCodigo.setBackground(java.awt.SystemColor.inactiveCaption);

        jLabel2.setText("Descripción");

        jLabel3.setText("Abreviatura");

        jLabel5.setText("Estado");

        jchkEstado.setText("Activo");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxtDescripcion)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jchkEstado)
                            .addComponent(jtxtAbreviatura, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 197, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtxtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtxtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtxtAbreviatura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jchkEstado))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Mantenimiento", new javax.swing.ImageIcon(getClass().getResource("/com/jsysacc/asistencia/view/resources/icons/px_16_16/btn_mant_16.png")), jPanel1); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbtnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnAceptar)
                    .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jbtnCancelarActionPerformed

    private void jbtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAceptarActionPerformed
        // TODO add your handling code here:

        if (!hayErroresInput()) {

            getEntity();

            try {
                if (esNuevo) {
                    if (logic.insert(entityVia)) {
                        JOptionPane.showMessageDialog(this, rbMensajes.getString("MSG_INS_OK"), rbMensajes.getString("MSG_MEN_PRI"), 1);
                        this.dispose();
                    } else {
                        JOptionPane.showMessageDialog(this, rbMensajes.getString("MSG_INS_ERROR"), rbMensajes.getString("MSG_MEN_PRI"), 0);
                    }
                } else {
                    if (logic.update(entityVia)) {
                        JOptionPane.showMessageDialog(this, rbMensajes.getString("MSG_UPD_OK") + " " + codVia , rbMensajes.getString("MSG_MEN_PRI"), 1);
                        this.dispose();
                    } else {
                        JOptionPane.showMessageDialog(this, rbMensajes.getString("MSG_UPD_ERROR"), rbMensajes.getString("MSG_MEN_PRI"), 0);
                    }
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), rbMensajes.getString("MSG_MEN_PRI"), 0);
            }

        }
    }//GEN-LAST:event_jbtnAceptarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        initMaster();
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormDialogMantVia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormDialogMantVia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormDialogMantVia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormDialogMantVia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FormDialogMantVia dialog = new FormDialogMantVia(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton jbtnAceptar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JCheckBox jchkEstado;
    private javax.swing.JTextField jtxtAbreviatura;
    private javax.swing.JTextField jtxtCodigo;
    private javax.swing.JTextField jtxtDescripcion;
    // End of variables declaration//GEN-END:variables

    public boolean isEsNuevo() {
        return esNuevo;
    }

    public void setEsNuevo(boolean esNuevo) {
        this.esNuevo = esNuevo;
    }

    public String getCodVia() {
        return codVia;
    }

    public void setCodVia(String codVia) {
        this.codVia = codVia;
    }

    @Override
    public boolean hayErroresInput() {
        if (JUB._vacio(this.jtxtDescripcion.getText())) {
            JOptionPane.showMessageDialog(this, "CAMPO DESCRIPCIÓN NO PUEDE ESTAR VACIO", rbMensajes.getString("MSG_MEN_PRI"), 1);
            JUB.selectionJTextField(this.jtxtDescripcion);
            return true;
        }

        if (JUB.toUpperBlank(this.jtxtDescripcion.getText()).length() > 50) {
            JOptionPane.showMessageDialog(this, "CAMPO DESCRIPCIÓN NO PUEDE TENER MAS DE 50 CARACTERES", rbMensajes.getString("MSG_MEN_PRI"), 1);
            JUB.selectionJTextField(this.jtxtDescripcion);
            return true;
        }

        if (JUB.toUpperBlank(this.jtxtAbreviatura.getText()).length() > 5) {
            JOptionPane.showMessageDialog(this, "CAMPO ABREVIATURA NO PUEDE TENER MAS DE 5 CARACTERES", rbMensajes.getString("MSG_MEN_PRI"), 1);
            JUB.selectionJTextField(this.jtxtAbreviatura);
            return true;
        }
        return false;
    }

    @Override
    public void getEntity() {
        entityVia = new Via();
        entityVia.setCod_via(JUB.toUpperBlank(this.jtxtCodigo.getText()));
        entityVia.setDescrip(JUB.toUpperBlank(this.jtxtDescripcion.getText()));
        entityVia.setCod_abr(JUB.toUpperBlank(this.jtxtAbreviatura.getText()));
        entityVia.setEstado(this.jchkEstado.isSelected() ? "A" : "I");
    }

    @Override
    public void initMaster() {
        this.jtxtCodigo.setDocument(new JTextFieldToUpperCase());
        this.jtxtDescripcion.setDocument(new JTextFieldToUpperCase());
        this.jtxtAbreviatura.setDocument(new JTextFieldToUpperCase());
        llenarData();

    }

    @Override
    public void setEntity(Object entity) {
        Via oVia = (Via) entity;
        this.jtxtCodigo.setText(oVia.getCod_via());
        this.jtxtDescripcion.setText(oVia.getDescrip());
        this.jtxtAbreviatura.setText(oVia.getCod_abr());
        this.jchkEstado.setSelected(oVia.getEstado().equals("A"));
    }

}
